<?php
// +-------------------------------------------------------------------
// | 
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Kcdns\Admin\Controller;
use Kcdns\Admin\Common\ModelCfg;

class CategoryController extends CommonController
{

    protected $nodes;

    protected $editRedirect = 2;
    
    protected function _initialize ()
    {
        parent::_initialize();
        
        // 分类树
        $cate = M('Category')->where()->order('pid,sort')->select();
        foreach ($cate as $k => $v)
        {
            $cate[$k]['url'] = U('edit', array(
                    ModelCfg::escape('category.id') => $v['id']
            ));
        }
        $this->nodes = list_to_tree($cate);
        $this->assign('nodes', $this->nodes);
    }

    public function index ()
    {
        // 批量排序
        if (IS_POST && I('post.flag') == 'sort')
        {
            $data = I('post.data');
            filter($data, [
                    [
                            'id' => 'required;int',
                            'sort' => 'required;int'
                    ]
            ]);
            foreach ($data as $v)
            {
                M('Category')->data([
                        'sort' => $v['sort']
                ])->where([
                        'id' => $v['id']
                ])->save();
            }
            $this->success();
        }
        
        if ($this->nodes)
        {
            $this->redirect('edit', array(
                    ModelCfg::escape('category.id') => $this->nodes[0]['id']
            ));
        }
        $this->display();
    }
}
